package com.seeapp.backend.file;

import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class FileUtil {

	/**
	 * 获取classpath目录下的文件
	 * 
	 * @param filePath
	 * @return
	 * @throws FileNotFoundException
	 */
	public static Resource getClassPathFile(String fileName) {
		return new ClassPathResource(fileName);
	}

	/**
	 * 获取classpath目录下excel模板文件
	 * 
	 * @param excelTemplateName
	 * @return
	 * @throws FileNotFoundException
	 */
	public static InputStream getExcelTemplateStream(String excelTemplateName) throws Exception {
		return getClassPathFile("template/" + excelTemplateName).getInputStream();
	}

	/**
	 * http文件下载时头部信息设置
	 * 
	 * @param response
	 */
	public static void setDowLoadFileHttpHead(HttpServletResponse response) {
		response.reset();
		response.setHeader("pragma", "no-cache");
		response.setContentType("application/octet-stream;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/msexcel;charset=UTF-8");
	}
	
	/**
	 * 设置下载文件时文件名
	 * @param request
	 * @param response
	 * @param dowLoadFileName
	 * @throws Exception
	 */
	public static void setDowLoadFileName(HttpServletRequest request, HttpServletResponse response,String dowLoadFileName) throws Exception {
		String userAgent = request.getHeader("User-Agent");
		if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
			dowLoadFileName = java.net.URLEncoder.encode(dowLoadFileName, "UTF-8");
		} else {
			dowLoadFileName = new String(dowLoadFileName.getBytes("UTF-8"), "ISO-8859-1");
		}
		response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", dowLoadFileName));
	}
}
